/**
 * Copyright (C)  2011  chen wei hua.
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 2.0
 * or any later version published by the Free Software Foundation;
 * with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU Free Documentation License".
 */
package com.javaeye.store.dao;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.javaeye.common.dto.DTO;
import com.javaeye.store.dto.Materials;
import com.javaeye.common.web.PageInfo;

public class MaterialsDAOHibernate extends HibernateDaoSupport implements MaterialsDAO {
	
	@SuppressWarnings("unchecked")
	public List<Materials> getAutoCompleteMaterials(final String name, final int size) {
		HibernateCallback action = new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Criteria crit = session.createCriteria(Materials.class);
				crit.add(Restrictions.or(Restrictions.like("code", "%" + name.trim() + "%")
						, Restrictions.like("name", "%" + name.trim() + "%")));
				crit.setFirstResult(0);
				crit.setMaxResults(size);
				return crit.list();
			}
		};
		return getHibernateTemplate().executeFind(action);
	}
	
	@SuppressWarnings("unchecked")
	public List getPageData(final DTO contidions, final PageInfo pageInfo) {
		HibernateCallback action = new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				
				int pageIndex = pageInfo.getPageIndex();
				int pageSize = pageInfo.getPageSize();
				Materials materials = (Materials)contidions;
				Criteria crit = session.createCriteria(Materials.class);
				String name = materials.getName().trim();
				if (!"".equals(name)) {
					crit.add(Restrictions.like("name", "%" + name + "%"));
				}
				String code = materials.getCode().trim();
				if (!"".equals(code)) {
					crit.add(Restrictions.like("code", "%" + code + "%"));
				}
				int category = materials.getCategory();
				if (-1 != category) {
					crit.add(Restrictions.eq("category", category));
				}
				crit.setProjection(Projections.rowCount());
				Integer rowNumber = (Integer)crit.uniqueResult();
				pageInfo.setCount(rowNumber);
				
				crit.setProjection(null);//取得了总数后,为了能够再次取得对象列表
				crit.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);//当hibernate采用关联的时候不使用这个返回的是个对象数组，加上这个返回的是当前列表的对象。
				crit.setFirstResult(pageIndex * pageSize);
				crit.setMaxResults(pageSize);
				return crit.list();
			}
		};
		return getHibernateTemplate().executeFind(action);
	}
	
	
	@Override
	public void saveMaterials(Materials materials) {
		getHibernateTemplate().saveOrUpdate(materials);
		logger.debug("Materials id set to: " + materials.getId());
	}

	@Override
	public Materials getMaterials(int materialsId) {
		return (Materials)getHibernateTemplate().get(Materials.class, materialsId);
	}
	
	@SuppressWarnings("unchecked")
	public long getCountByCategoryId(int categoryId) {
		final String queryString = "select count(m.id) from Materials m where m.category=?";
		List result = getHibernateTemplate().find(queryString, categoryId);
		long count = 0;
		if (result.size() > 0) {
			count = (Long)result.get(0);
		}
		return count;
	}
	
	@SuppressWarnings("unchecked")
	public Materials getMaterialsByCode(String code) {
		final String queryString = "from Materials m where m.code=?";
		List result = getHibernateTemplate().find(queryString, code);
		if (result == null || result.size() == 0) {
			return null;
		}
		return (Materials)result.get(0);
	}

	@Override
	public void removeMaterials(int materialsId) {
		Object o = getHibernateTemplate().load(Materials.class, materialsId);
		getHibernateTemplate().delete(o);
	}

}
